import { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Space,
  Tag,
  Spin,
  Card,
  Button,
  message,
  Divider,
  Popconfirm,
  Modal,
} from 'antd';
import {
  getOrderInfo,
  cancelOrder,
  createNative,
  queryPayStatus,
} from '../../../api';
import { useParams } from 'react-router-dom';
import order from '../../../redux/reducers/order';
import codeLoginWechat from '../../../assets/images/code_login_wechat.png';
import {
  WechatOutlined,
  CheckOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { QRious } from 'react-qrious';

const OrderDetail = (props) => {
  const { id } = useParams();
  const [orderInfo, setOrderInfo] = useState({});
  const [isPayModalVisible, setIsPayModalVisible] = useState(false);
  const [codeUrl, setCodeUrl] = useState('');
  const [intervalId, setIntervalId] = useState(0);

  useEffect(() => {
    initData();
  }, []);

  const initData = async () => {
    const orderInfoData = await getOrderInfo(id);
    setOrderInfo(orderInfoData);
  };

  const cancelConfirm = async () => {
    await cancelOrder(id);
    await initData();
  };

  const onPayOrder = async () => {
    await setIsPayModalVisible(true);
    const result = await createNative(id);
    setCodeUrl(result.codeUrl);

    if (intervalId) {
      clearInterval(intervalId);
      setIntervalId(0);
      return;
    }

    const newIntervalId = setInterval(async () => {
      const result = await queryPayStatus(id);
      if (result) {
        console.log(1);
        initData();
        clearInterval(newIntervalId);
        setIsPayModalVisible(false);
      }
    }, 3000);
    setIntervalId(newIntervalId);
  };

  const handlePayOk = () => {
    setIsPayModalVisible(false);
  };

  const handlePayCancel = () => {
    setIsPayModalVisible(false);
  };

  if (!orderInfo.id)
    return (
      <div className='m-l-30 m-r-30 m-b-30'>
        <Spin />
      </div>
    );

  return (
    <div className='m-l-30 m-r-30 m-b-30'>
      <Modal
        title='支付挂号订单'
        visible={isPayModalVisible}
        onOk={handlePayOk}
        onCancel={handlePayCancel}
        width='300px'
        okText={<span style={{ color: 'white' }}>确认</span>}
        cancelText='取消'
      >
        {codeUrl.length > 0 && (
          <QRious value={codeUrl} style={{ width: '100%', height: '100%' }} />
        )}
      </Modal>

      <h2>挂号详情</h2>
      <Row justify='space-between'>
        <Col flex='300px' style={{ fontSize: '20px' }}>
          <Tag icon={<CheckOutlined />} color='#87d068'>
            <span style={{ color: 'white' }}>
              {orderInfo.param.orderStatusString}
            </span>
          </Tag>
        </Col>
        <Col>
          <Row>
            <Space>
              <Col>
                <img
                  src={codeLoginWechat}
                  style={{ width: '40px', height: '40px' }}
                />
              </Col>
              <Col>
                <div>
                  微信 <WechatOutlined style={{ color: 'green' }} /> 关注
                  “北京114预约挂号”
                  <br />
                  “快速预约挂号”
                </div>
              </Col>
            </Space>
          </Row>
        </Col>
      </Row>

      <Divider />

      <Row gutter={16}>
        <Col span={12}>
          <Card>
            <Space direction='vertical'>
              <Row>
                <Col>就诊人信息：</Col>
                <Col flex='auto'>{orderInfo.patientName}</Col>
              </Row>
              <Row>
                <Col>就诊日期：</Col>
                <Col flex='auto'>
                  {orderInfo.reserveDate}
                  {orderInfo.reserveTime == 0 ? '上午' : '下午'}
                </Col>
              </Row>

              <Row>
                <Col>就诊医院：</Col>
                <Col flex='auto'>{orderInfo.hosname}</Col>
              </Row>

              <Row>
                <Col>就诊科室：</Col>
                <Col flex='auto'>{orderInfo.depname}</Col>
              </Row>

              <Row>
                <Col>医生职称：</Col>
                <Col flex='auto'>{orderInfo.title}</Col>
              </Row>

              <Row>
                <Col>医事服务费：</Col>
                <Col flex='auto' style={{ color: 'red', fontWeight: 'bold' }}>
                  {orderInfo.amount}元
                </Col>
              </Row>
              <Row>
                <Col>挂号单号：</Col>
                <Col flex='auto'>{orderInfo.outTradeNo}</Col>
              </Row>
              <Row>
                <Col>挂号时间：</Col>
                <Col flex='auto'>{orderInfo.createTime}</Col>
              </Row>
            </Space>
          </Card>

          <Space className='m-t-10'>
            {(orderInfo.orderStatus == 0 || orderInfo.orderStatus == 1) && (
              <>
                <Popconfirm
                  title='确认取消预约？'
                  onConfirm={cancelConfirm}
                  okText={<span style={{ color: 'white' }}>确认</span>}
                  cancelText='取消'
                  icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                >
                  <Button>取消预约</Button>
                </Popconfirm>
                {orderInfo.orderStatus == 0 && (
                  <Button type='primary' onClick={onPayOrder}>
                    <span style={{ color: 'white' }}>支付</span>
                  </Button>
                )}
              </>
            )}
          </Space>
        </Col>
        <Col span={12}>
          <Card title={<span style={{ color: 'white' }}>注意事项</span>}>
            <ol>
              <li>
                请确认就诊人信息是否准确，若填写错误将无法取号就诊，损失由本人承担；
              </li>
              <li style={{ color: 'red' }}>
                【取号】就诊当天需在{orderInfo.fetchTime}
                在医院取号，未取号视为爽约，该号不退不换；
              </li>
              <li>
                【退号】在{orderInfo.quitTime}前可在线退号
                ，逾期将不可办理退号退费；
              </li>
              <li>
                北京114预约挂号支持自费患者使用身份证预约，同时支持北京市医保患者使用北京社保卡在平台预约挂号。请于就诊当日，携带预约挂号所使用的有效身份证件到院取号；
              </li>
              <li>请注意北京市医保患者在住院期间不能使用社保卡在门诊取号。</li>
            </ol>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default OrderDetail;
